package com.hice.demo.java.concurrent;

import java.util.concurrent.Exchanger;

/**
 * 交换机 Exchanger
 *
 * @author hyson
 * @create 2017-03-13 11:47
 */
public class ExchangerDemo {

    /**
     * 交换对象的动作由 Exchanger 的两个 exchange() 方法的其中一个完成
     *
     * @param args
     */
    public static void main(String[] args) {
        Exchanger exchanger = new Exchanger();

        ExchangerRunnable exchangerRunnable1 =
                new ExchangerRunnable(exchanger, "A");

        ExchangerRunnable exchangerRunnable2 =
                new ExchangerRunnable(exchanger, "B");

        new Thread(exchangerRunnable1).start();
        new Thread(exchangerRunnable2).start();
    }

    static class ExchangerRunnable implements Runnable {

        Exchanger exchanger = null;
        Object object = null;

        public ExchangerRunnable(Exchanger exchanger, Object object) {
            this.exchanger = exchanger;
            this.object = object;
        }

        public void run() {
            try {
                Object previous = this.object;

                this.object = this.exchanger.exchange(this.object);

                System.out.println(
                        Thread.currentThread().getName() +
                                " exchanged " + previous + " for " + this.object
                );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
